<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="街道名称" prop="streetName">
        <el-input
          v-model="queryParams.streetName"
          placeholder="请输入街道名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="街道编码" prop="streetCode">
        <el-input
          v-model="queryParams.streetCode"
          placeholder="请输入街道编码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="区编码" prop="districtCode">
        <el-input
          v-model="queryParams.districtCode"
          placeholder="请输入区编码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="区名称" prop="districtName">
        <el-input
          v-model="queryParams.districtName"
          placeholder="���输入区名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['house:street:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['house:street:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['house:street:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['house:street:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="streetList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="街道ID" align="center" prop="streetId" />
      <el-table-column label="街道名称" align="center" prop="streetName" />
      <el-table-column label="街道编码" align="center" prop="streetCode" />
      <el-table-column label="所属省" align="center" prop="provinceCode">
        <template slot-scope="scope">
          <span>{{ getProvinceName(scope.row.provinceCode) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="所属市" align="center" prop="cityCode">
        <template slot-scope="scope">
          <span>{{ getCityName(scope.row.cityCode) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="所属区" align="center" prop="districtCode">
        <template slot-scope="scope">
          <span>{{ getDistrictName(scope.row.districtCode) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['house:street:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['house:street:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改街道对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="街道名称" prop="streetName">
          <el-input v-model="form.streetName" placeholder="请输入街道名称" />
        </el-form-item>
        <el-form-item label="街道编码" prop="streetCode">
          <el-input v-model="form.streetCode" placeholder="请输入街道编码" />
        </el-form-item>
        <el-form-item label="省份" prop="provinceCode">
          <el-select v-model="form.provinceCode" placeholder="请选择省份" @change="handleProvinceChange">
            <el-option
              v-for="province in provinceOptions"
              :key="province.provinceCode"
              :label="province.provinceName"
              :value="province.provinceCode"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="所属市" prop="cityCode">
          <el-select v-model="form.cityCode" placeholder="请选择所属市" @change="handleCityChange">
            <el-option
              v-for="city in cityOptions"
              :key="city.cityCode"
              :label="city.cityName"
              :value="city.cityCode"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="所属区" prop="districtCode">
          <el-select v-model="form.districtCode" placeholder="请选择所属区" @change="handleDistrictChange">
            <el-option
              v-for="district in districtOptions"
              :key="district.districtCode"
              :label="district.districtName"
              :value="district.districtCode"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listStreet, getStreet, delStreet, addStreet, updateStreet } from "@/api/house/street";
import { listProvince } from "@/api/house/province";
import { listCity } from "@/api/house/city";
import { listDistrict, listDistrictOptions } from "@/api/house/district";

export default {
  name: "Street",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 街道表格数据
      streetList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 区选项数组
      districtOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        streetName: null,
        streetCode: null,
        districtCode: null,
        districtName: null,
        provinceCode: undefined,
        cityCode: undefined
      },
      // 表单参数
      form: {
        streetId: undefined,
        streetName: undefined,
        streetCode: undefined,
        provinceCode: undefined,
        cityCode: undefined,
        districtCode: undefined,
        districtName: undefined
      },
      // 表单校验
      rules: {
        streetName: [
          { required: true, message: "街道名称不能为空", trigger: "blur" }
        ],
        streetCode: [
          { required: true, message: "街道编码不能为空", trigger: "blur" }
        ],
        districtCode: [
          { required: true, message: "区编码不能为空", trigger: "blur" }
        ],
        provinceCode: [
          { required: true, message: "省份不能为空", trigger: "change" }
        ],
        cityCode: [
          { required: true, message: "所属市不能为空", trigger: "change" }
        ]
      },
      // 省份选项数组
      provinceOptions: [],
      // 市选项数组
      cityOptions: [],
      // 区域选项数组
      districtOptions: []
    };
  },
  created() {
    this.getList();
    this.getProvinceOptions();
    this.getCityOptions();
    this.getDistrictOptions();
  },
  methods: {
    /** 查询街道列表 */
    getList() {
      this.loading = true;
      listStreet(this.queryParams).then(response => {
        this.streetList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 获取省份列表 */
    getProvinceOptions() {
      listProvince().then(response => {
        this.provinceOptions = response.rows;
      });
    },
    /** 获取市列表 */
    getCityOptions(provinceCode) {
      listCity({ provinceCode: provinceCode }).then(response => {
        this.cityOptions = response.rows;
        this.form.cityCode = undefined;
        this.form.districtCode = undefined;
        this.form.districtName = undefined;
        this.districtOptions = [];
      });
    },
    /** 省份选择框变化事件处理 */
    handleProvinceChange(value) {
      this.getCityOptions(value);
    },
    /** 市选择框变化事件处理 */
    handleCityChange(value) {
      const selectedCity = this.cityOptions.find(city => city.cityCode === value);
      if (selectedCity) {
        this.getDistrictOptions(value);
      }
    },
    /** 获取区域选项（用于下拉框） */
    getDistrictOptions() {
      listDistrictOptions().then(response => {
        this.districtOptions = response.rows;
      });
    },
    /** 远程搜索区域 */
    remoteDistrictMethod(query) {
      if (query !== '') {
        this.districtLoading = true;
        listDistrictOptions({
          districtName: query
        }).then(response => {
          this.districtOptions = response.rows;
          this.districtLoading = false;
        });
      } else {
        this.districtOptions = [];
      }
    },
    /** 区选择框变化事件处理 */
    handleDistrictChange(value) {
      const selectedDistrict = this.districtOptions.find(district => district.districtCode === value);
      if (selectedDistrict) {
        this.form.districtName = selectedDistrict.districtName;
      }
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        streetId: null,
        streetName: null,
        streetCode: null,
        districtCode: null,
        districtName: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.streetId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加街道";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const streetId = row.streetId || this.ids
      getStreet(streetId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改街道";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.streetId != null) {
            updateStreet(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addStreet(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const streetIds = row.streetId || this.ids;
      this.$modal.confirm('是否确认删除街道编号为"' + streetIds + '"的数据项？').then(function() {
        return delStreet(streetIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('house/street/export', {
        ...this.queryParams
      }, `street_${new Date().getTime()}.xlsx`)
    },
    /** 获取省份名称 */
    getProvinceName(provinceCode) {
      let province = this.provinceOptions.find(item => item.provinceCode === provinceCode);
      return province ? province.provinceName : '';
    },
    /** 获取城市名称 */
    getCityName(cityCode) {
      let city = this.cityOptions.find(item => item.cityCode === cityCode);
      return city ? city.cityName : '';
    },
    /** 获取区域名称 */
    getDistrictName(districtCode) {
      let district = this.districtOptions.find(item => item.districtCode === districtCode);
      return district ? district.districtName : '';
    }
  }
};
</script> 